package com.xuelang.pipeline.app.pipeline.impl;

import com.xuelang.pipeline.app.pipeline.SonarqubeClient;
import com.xuelang.pipeline.app.pipeline.SonarqubeService;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.pipeline.dto.MeasDTO;
import com.xuelang.pipeline.client.resource.dto.ToolChainQuery;
import com.xuelang.pipeline.client.resource.enums.ToolChainTypeEnum;
import com.xuelang.pipeline.domain.resource.ToolChain;
import com.xuelang.pipeline.domain.resource.service.ToolChainDomainService;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.slf4j.Slf4jLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author liuyuan.ly
 * @since 2024/7/22 16:03
 */
@Service
public class SonarqubeServiceImpl implements SonarqubeService {

    /**
     * feign编码器
     */
    @Autowired
    private Encoder encoder;
    /**
     * feign解码器
     */
    @Autowired
    private Decoder decoder;

    @Autowired
    private ToolChainDomainService toolChainDomainService;

    @Override
    public MeasDTO getSonarScanResult(String uniqueCode) {
        ToolChainQuery query = new ToolChainQuery();
        query.setType(ToolChainTypeEnum.TYPE_QA.getTypeKey());
        PageRecord<ToolChain> toolChainPageRecord = toolChainDomainService.pageList(1, 1, query);
        ToolChain toolChain = toolChainPageRecord.getRecords().get(0);
        SonarqubeClient sonarClient = Feign.builder()
                .decoder(decoder)
                .encoder(encoder)
                .options(new Request.Options(3000, 3500))
                .retryer(new Retryer.Default(1000, 1000, 1))
                .logger(new Slf4jLogger(SonarqubeClient.class))
                .logLevel(Logger.Level.FULL)
                .requestInterceptor(new BasicAuthRequestInterceptor(toolChain.getUsername(), toolChain.getPassword()))
                .target(SonarqubeClient.class, toolChain.getServer());


        MeasDTO sonarDetail = sonarClient.getSonarDetail(uniqueCode, "bugs,code_smells,vulnerabilities");
        return sonarDetail;


    }

}
